package com.webtest.authoritydemo;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2018-08-19 20:48
 */
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 4755302377678536645L;
    private UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methodName = request.getParameter("method");
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取name
        String userName = request.getParameter("loginname");
        boolean checkName = false;
        //2.获取UserDao获取用户信息，对用户信息进行判断，如果
        // 把用户信息放入到HttpSession中
        if (StringUtils.isEmpty(userName)) {
            request.setAttribute("message", "登录名输入错误！");
            checkName = true;
        } else if (!userDao.exit(userName)) {
            request.setAttribute("message", "用户不存在！");
            checkName = true;
        }
        if (checkName) {
            request.getRequestDispatcher("/authdemo/login.jsp").forward(request, response);
            return;
        }
        // 3.如果登陆成功，将用户名放入到HttpSession中
        request.getSession().setAttribute("loginName", userName);
        response.sendRedirect(request.getContextPath() + "/authdemo/articles.jsp");
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取httpSession
        HttpSession session = request.getSession();
        //2.使httpSession失效
        session.invalidate();
        //3.重定向到login.jsp
        response.sendRedirect(request.getContextPath() + "/authdemo/login.jsp");
    }
}
